/*
 * JF Updater: Auto-updater for modified Android OS
 *
 * Copyright (c) 2009 Sergi Vélez
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

package jfupdater.service;

import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.text.MessageFormat;
import java.util.List;

import jfupdater.ui.R;
import jfupdater.ui.UpdateProcessInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;


public class UpdateService extends Service {
	
	public static UpdateService INSTANCE;
	
	private static final String TAG = "UpdateService";
	
	public static final String KEY_REQUEST = "jfupdater.request";
	
	public static final int REQUEST_CHECK_FOR_UPDATES = 1;
	
	
	private Looper mServiceLooper;
	private ServiceHandler mServiceHandler;
	private IUpdateServer mUpdateServer;
	private NotificationManager mNM;
	
	private final class ServiceHandler extends Handler {

		public ServiceHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
            Bundle arguments = (Bundle)msg.obj;
            
            int request = arguments.getInt(KEY_REQUEST); 
            switch(request) {
            	case REQUEST_CHECK_FOR_UPDATES:
					checkForUpdates();
					break;
            	default:
            		Log.e(TAG, "Unknown request ID:" + request);
            }

            Log.i("ServiceStartArguments", "Done with #" + msg.arg1);
            stopSelf(msg.arg1);
		}
	}
	

	@Override
	public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        
		HandlerThread thread = new HandlerThread(TAG);
        thread.start();
        
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
		URI uri = URI.create(getResources().getString(R.string.conf_update_server_url));
        mUpdateServer = new PlainTextUpdateServer(uri, this);
		
		INSTANCE = this;
	}

	@Override
	public void onStart(Intent intent, int startId) {
        Log.i(TAG, "Starting #" + startId + ": " + intent.getExtras());
        
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent.getExtras();
        mServiceHandler.sendMessage(msg);
        Log.d("ServiceStartArguments", "Sending: " + msg);
	}

	@Override
	public void onDestroy() {
		mServiceLooper.quit();
		INSTANCE = null;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	private void checkForUpdates() {
		Resources res = getResources();
		
		List<UpdateInfo> availableUpdates;
		try {
			Log.i(TAG, "Checking for updates...");
			availableUpdates = mUpdateServer.getAvailableUpdates();
		} catch (IOException ex) {
			Log.e(TAG, "IOEx while checking for updates", ex);
			notificateCheckError();
			return;
		} catch (RuntimeException ex) {
			Log.e(TAG, "RuntimeEx while checking for updates", ex);
			notificateCheckError();
			return;
		}
		
		int updateCount = availableUpdates.size();
		Log.i(TAG, updateCount + " update(s) found");
		
		if(updateCount > 0) {
			Intent i = new Intent(this, UpdateProcessInfo.class)
							.putExtra(UpdateProcessInfo.KEY_REQUEST, UpdateProcessInfo.REQUEST_NEW_UPDATE_LIST)
							.putExtra(UpdateProcessInfo.KEY_UPDATE_LIST, (Serializable)availableUpdates);
			
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i,
												PendingIntent.FLAG_ONE_SHOT);
			
			Notification notification = new Notification(android.R.drawable.stat_notify_sync,
												res.getString(R.string.not_new_updates_found_ticker),
												System.currentTimeMillis());
			
			String text = MessageFormat.format(res.getString(R.string.not_new_updates_found_body), updateCount);
			notification.setLatestEventInfo(this, res.getString(R.string.not_new_updates_found_title), text, contentIntent);
			
			//Use a resourceId as an unique identifier
			mNM.notify(R.string.not_new_updates_found_title, notification);
		} else {
			Log.i(TAG, "No updates found");
		}
	}

	private void notificateCheckError() {
		Resources res = getResources();
		Intent i = new Intent(this, UpdateProcessInfo.class)
						.putExtra(UpdateProcessInfo.KEY_REQUEST, UpdateProcessInfo.REQUEST_UPDATE_CHECK_ERROR);

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i,
															PendingIntent.FLAG_ONE_SHOT);
		
		Notification notification = new Notification(android.R.drawable.stat_notify_error,
												res.getString(R.string.not_update_check_error_ticker),
												System.currentTimeMillis());
		
		notification.setLatestEventInfo(
							this,
							res.getString(R.string.not_update_check_error_title),
							res.getString(R.string.not_update_check_error_body),
							contentIntent);
		
		//Use a resourceId as an unique identifier
		mNM.notify(R.string.not_update_downloaded_title, notification);
	}

}
